const app = getApp()
const height = wx.getSystemInfoSync().windowHeight //系统高度
const width = wx.getSystemInfoSync().windowWidth //系统宽度
const rpxtopx = width / 750 //rpx转px系数
const {
  userReviewList
} = require('../../../api/api')
import * as echarts from '../../../components/ec-canvas/echarts.min';
// DISC
const type1 = {
  "buttonColor": "#C15870",
  "buttonTextColor": "#ffffff",
  "bgColor": "#FDEFEC",
  "testBg": "https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/test_bg.png",
  "bgImg": "https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/disc_bg.png"
}
//霍兰德
const type2 = {
  "buttonColor": "#434094",
  "buttonTextColor": "#ffffff",
  "bgColor": "#EBF1FF",
  "bgImg": "https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/huo_bg.png",
  "testBg": "https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/test_bg.png",
}
//九型人格
const type3 = {
  "buttonColor": "#9F969B",
  "buttonTextColor": "#ffffff",
  "bgColor": "#ECE9F2",
  "bgImg": "https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/nine_bg.png",
  "testBg": "https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/test_bg.png",
}
//MBTI
const type4 = {
  "buttonColor": "#FCCE00",
  "buttonTextColor": "#333333",
  "bgColor": "rgba(252, 206, 0, 0.3)",
  "testBg": "https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/test_bg.png",
  "bgImg": "https://ehsimg.oss-cn-beijing.aliyuncs.com/images/1652581357855.png"
}
var Chart1 = null;
var Chart2 = null;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    info: {
      analysis: null,
      createBy: "奥特曼吃地瓜",
      createTime: "2022-04-18 10:32:08",
      id: 23,
      picUrl: null,
      professionRecommend: null,
      result: "很好",
      resultDesc: null,
      type: type1,
      review: {},
      reviewId: 2,
      reviewNo: "CP202204180204309972",
      score: 10,
      indicator: [],
      scoreData: {},
      status: 3,
      username: "奥特曼吃地瓜"
    },
    ec: {
      onInit: function (canvas, width, height, dpr) {
        Chart1 = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr
        });
        canvas.setChart(Chart1);
        return Chart1;
      }
    },
    ec1: {
      onInit: function (canvas, width, height, dpr) {
        Chart2 = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr
        });
        canvas.setChart(Chart2);
        return Chart2;
      }
    },

    bottomLift: app.globalData.bottomLift,
    windowHeight: app.globalData.windowHeight,
    canvasW: width, //画布宽度
    canvasType: false,
    count: 0,
    id: null
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.param) {
      this.setData({
        resultData: JSON.parse(decodeURIComponent(options.param))
      })
      this.analysisData()
    }
    if (options.id) {
      this.setData({
        id: options.id
      })
      this.loadData()
    }
  },
  async loadData() {
    wx.showLoading({
      title: '加载中',
    })
    const {
      id
    } = this.data
    const params = {
      status: 3,
      id,
    }
    const {
      result
    } = await userReviewList(params)
    wx.hideLoading()
    result.map((item) => {
      let value = JSON.parse(item.review.description)
      for (let key in value) {
        item[key] = value[key]
      }
    })
    this.setData({
      resultData: result[0]
    })
    this.analysisData()
  },
  analysisData() {
    const info = this.data.resultData
    console.log(info)
    const {
      indicator,
      scoreData
    } = info.scoreStatistics
    const {
      reviewScoreVoList
    } = info
    let count = 0
    const newArr = indicator.map((item) => {
      return item.max
    })
    var max = newArr.sort(function (a, b) {
      return b - a
    })
    const {
      reviewId
    } = info
    let {
      type
    } = this.data
    switch (reviewId) {
      case 2:
        type = type4
        break;
      case 3:
        type = type2
        break;
      case 4:
        type = type1
        break;
      case 5:
        type = type3
        break;
      case 6:
        type = type2
        break;
      default:
        type = type1
        // 如果没有与表达式相同的值，则执行该代码
    }

    var level = info.reviewResultVoList.map(e => {
      return e.level
    }).join('')
    var result = info.reviewResultVoList.map(e => {
      return e.result
    }).join('')
    if (result) {
      var srcreg = /<img [^>]*src=['"]([^'"]+)[^>]*>/g
      var heightreg = /<img [^>]*height=['"]([^'"]+)[^>]*>/g
      var srcList = this.getList(result, srcreg)
      var heighList = this.getList(result, heightreg)
      var resultList = []
      srcList.map((e, i) => {
        heighList.map((item, index) => {
          if (i == index) {
            let obj = {
              src: e,
              height: item
            }
            resultList.push(obj)

          }
        })
      })
    }
    this.setData({
      info,
      level,
      result,
      type,
      resultList,
      indicator,
      scoreData,
      count: max[0],
      reviewScoreVoList
    })
    wx.setNavigationBarTitle({
      title: info.review.shortTitle + info.review.title,
    })
    this.setEcharts()
  },
  setEcharts() {
    const {
      reviewId
    } = this.data.info
    const {
      indicator,
      scoreData,
      count,
      reviewScoreVoList
    } = this.data
    const data = indicator.map((item) => {
      return item.name
    })
    const indicatorCopy = JSON.parse(JSON.stringify(indicator))
    //获取真实indicator
    indicatorCopy.map((item) => {
      item.max = count
    })
    // 柱状图
    const data1 = indicator.map((item) => {
      return item.max
    })
    let max = Math.max.apply(Math, reviewScoreVoList.map(e => {
      return e.activity
    }))
    const reviewScoreVoList1 = reviewScoreVoList.map((item) => {
      return {
        value: item.activity,
        max: max,
        name: item.code
      }
    })
    let data2 = reviewScoreVoList.map((item) => {
      return item.activity
    })

    let lineComponent = this.selectComponent('#mychart-dom-graph');
    let lineComponent1 = this.selectComponent('#mychart-dom-graph1');
    if (reviewId === 4) {
      lineComponent.init((canvas, width, height, dpr) => {
        let chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr, // new
        });
        // 设置数据
        // this.chart = chart;
        chart.setOption({
          backgroundColor: '#ffffff',
          color: ['#E495A9'],
          xAxis: {
            type: 'category',
            data: data,
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            splitLine: {
              show: false
            },
          },
          yAxis: {
            type: 'value',
            show: false
          },
          series: [{
              data: data1,
              type: 'bar',
              label: {
                show: true,
                formatter: '{c}',
                position: 'top',
                color: '#333'
              },
              barWidth: 32
            },

          ]
        })
      });

    } else if (reviewId === 3 || reviewId === 6) {
      lineComponent.init((canvas, width, height, dpr) => {
        let chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr, // new
        });
        chart.setOption({
          backgroundColor: "#ffffff",
          color: ["#DDD3DA"],
          radar: {
            // shape: 'circle',
            splitNumber: 6,
            splitLine: {
              lineStyle: {
                color: [
                  '#6C69B5'
                ]
              }
            },
            splitArea: {
              show: false
            },
            axisLine: {
              lineStyle: {
                color: '#6C69B5'
              }
            },
            indicator: indicatorCopy
          },
          series: [{
            name: '预算 vs 开销',
            type: 'radar',
            areaStyle: {
              color: 'rgba(67, 64, 148, 0.3)'
            },
            lineStyle: {
              width: 0
            },
            symbolSize: 0,
            data: [{
              value: data1,
              name: '预算'
            }, ]
          }]
        })
      });

    } else if (reviewId === 5) {
      lineComponent.init((canvas, width, height, dpr) => {
        let chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr, // new
        });
        chart.setOption({
          backgroundColor: "#ffffff",
          color: ["#DDD3DA"],
          radar: {
            shape: 'circle',
            splitNumber: 9,
            splitLine: {
              lineStyle: {
                color: [
                  '#DDD3DA'
                ]
              }
            },
            splitArea: {
              show: false
            },
            axisLine: {
              lineStyle: {
                color: '#DDD3DA'
              }
            },
            indicator: indicatorCopy
          },
          series: [{
            name: scoreData.name,
            type: 'radar',
            label: {
              color: '#000'
            },
            areaStyle: {
              color: 'rgba(221, 211, 218,.6)'
            },
            lineStyle: {
              width: 0
            },
            symbolSize: 0,
            data: [{
              value: data1,
              name: '预算'
            }, ]
          }]
        })
      });
      lineComponent1.init((canvas, width, height, dpr) => {
        let chart1 = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr, // new
        });
        chart1.setOption({
          backgroundColor: '#ffffff',
          color: ['#DDD3DA'],
          xAxis: {
            type: 'category',
            data: data,
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            splitLine: {
              show: false
            },
          },
          yAxis: {
            type: 'value',
            show: false
          },
          series: [{
              data: data1,
              type: 'bar',
              label: {
                show: true,
                formatter: '{c}',
                position: 'top',
                color: '#333'
              },
            },

          ]
        })
      });

    } else {
      lineComponent.init((canvas, width, height, dpr) => {
        let chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr, // new
        });
        chart.setOption({
          backgroundColor: "#ffffff",
          color: ["#DDD3DA"],
          radar: {
            // shape: 'circle',
            splitNumber: 1,
            splitLine: {
              lineStyle: {
                color: [
                  '#FCCE00'
                ]
              }
            },
            splitArea: {
              show: false
            },
            axisLine: {
              lineStyle: {
                color: '#FCCE00',
              },
            },
            indicator: indicatorCopy

          },
          series: [{
            name: '预算 vs 开销',
            type: 'radar',
            areaStyle: {
              color: '#FCCE00'
            },
            lineStyle: {
              width: 1,
              color: '#FCCE00'
            },
            symbolSize: 4,
            data: [{
              value: data1,
              name: '预算'
            }, ]
          }]
        })
      });

    }


  },

  onReady: function () {

  },
  async bindShare() {
    wx.showLoading({
      title: '图片正在生成'
    })
    // echarts单个图表的宽高，本文是实际宽高转换为px并缩小至70%，可根据自身设置
    const chart = {
      w: (width - 30 * rpxtopx) * 0.7,
      h: 450 * rpxtopx * 0.7
    }
    const {
      resultList
    } = this.data
    var height = 0
    resultList.map(e => {
      height += parseInt(e.height)
    })
    // 画布高度根据自身绘制内容设置
    var num = 0
    if (this.data.info.reviewId === 5) {
      num = chart.h
    }
    this.setData({
      canvasH: 650 + height + num,
      canvasType: true,
      height
    })
    // 绘制
    await this.drawShareImage(chart)
  },
  getImgSrc(richtext) {
    let imgList = []
    richtext.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
      imgList.push(capture);
    });
    return imgList;
  },
  async drawShareImage(chart) {
    var that = this;
    // 获取绘图上下文, 参数为canvas-id
    const ctx = wx.createCanvasContext('myCanvas')
    //绘制背景
    ctx.fillStyle = '#EBF1FF'
    ctx.fillRect(0, 0, that.data.canvasW, that.data.canvasH + 230)
    // 绘制顶部图片
    const topImage = await that.getNetworkImage(that.data.type.bgImg)
    ctx.drawImage(topImage.path, 0, 0, topImage.width, topImage.height, 0, 0, that.data.canvasW, 185);
    //绘制白色矩形,绘制起始位置
    var length = 150
    if (that.data.info.reviewId === 5) {
      length += chart.h
    }
    var startY = 130
    ctx.fillStyle = 'white'
    that.roundRect(ctx, 16, startY, that.data.canvasW - 32, that.data.canvasH - length, 16)
    //logo位置
    var startY = 162
    const logoImage = await that.getNetworkImage("https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/test_bg.png")
    var startX = (that.data.canvasW - 95) / 2
    ctx.drawImage(logoImage.path, 0, 0, logoImage.width, logoImage.height, startX, startY, 95, 95);
    //绘制logo中的标题
    ctx.font = '60px'
    ctx.fillStyle = this.data.type.buttonColor
    startY += 50
    startX = (that.data.canvasW - ctx.measureText(that.data.level).width) / 2
    ctx.fillText(that.data.level, startX, startY)
    // 绘制标题
    // ctx.font = '36px';
    // ctx.fillStyle = this.data.type.buttonColor
    // startY += 95 + 25
    // startX = (that.data.canvasW - ctx.measureText(that.data.level).width) / 2
    // ctx.fillText(that.data.level, startX, startY)
    //绘制分隔图片
    startY += 10 + 70
    ctx.drawImage('./images/icon_dash_line.png', 16, startY, that.data.canvasW - 32, 29);
    // 绘制echarts图表
    const chart1 = await that.getChartImage('#mychart-dom-graph')
    startY += 29 + 10
    ctx.drawImage(chart1, (that.data.canvasW - chart.w) / 2, startY, chart.w, chart.h);
    ctx.save();
    // 绘制echarts图表2
    const {
      info
    } = this.data
    if (info.reviewId === 5) {
      const chart2 = await that.getChartImage('#mychart-dom-graph1')
      startY += chart.h
      ctx.drawImage(chart2, (that.data.canvasW - chart.w) / 2, startY, chart.w, chart.h);
      ctx.save();
    }

    // 绘制参考职业
    startY += chart.h + 34
    if (this.data.info.reviewId === 3 && that.data.info.reviewProfessional) {
      var profession = '参考职业: ' + that.data.info.reviewProfessional.profession
      // console.log(profession.length)
      ctx.font = '28px';
      ctx.fillStyle = this.data.type.buttonColor
      startX = 40
      that.drawText(ctx, profession, startX, startY, 148, this.data.canvasW - 165);
      startY += 50
    }


    // ctx.fillText("参考职业：" + profession, startX, startY)
    startY += 10

    //绘制分隔图片
    ctx.drawImage('./images/icon_dash_line.png', 16, startY, that.data.canvasW - 32, 29);
    // 绘制描述
    // ctx.font = '28px';
    // ctx.fillStyle = "#333333"
    // startX = 40
    // startY += 29 + 10
    // ctx.fillText("" + that.data.info.result, startX, startY, that.data.canvasW - 2 * startX)

    startY += 29
    startX = 20
    const {
      resultList,
      height
    } = this.data
    for (let i = 0; i < resultList.length; i++) {
      var bottomImage = await that.getNetworkImage(resultList[i].src)
      if (i > 0) {
        startY += parseInt(resultList[i].height)
      }
      if (i > 0 && info.reviewId === 5) {
        startY -= 120
      }
      //  console.log(startY)
      ctx.drawImage(bottomImage.path, 0, 0, this.data.canvasW - 45, resultList[i].height, startX, startY, this.data.canvasW - 45, resultList[i].height / 1);
    }
    that.setData({
      canvasH: 650 + height + 20,
      // canvasType: true
    })
    //绘制
    ctx.draw(false, function () {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: (res) => {
          const tempFilePath = res.tempFilePath
          // 判断是否授权保存到相册
          that.checkAuthSetting(tempFilePath)
        },
        fail: () => {}
      })
    })
  },
  //文本换行 参数：1、canvas对象，2、文本 3、距离左侧的距离 4、距离顶部的距离 5、6、文本的宽度
  drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
    var lineWidth = 0;
    var lastSubStrIndex = 0; //每次开始截取的字符串的索引
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > canvasWidth) {
        ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
        initHeight += 16; //16为字体的高度
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 30;
      }
      if (i == str.length - 1) { //绘制剩余部分
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
    // 标题border-bottom 线距顶部距离
    titleHeight = titleHeight + 10;
    return titleHeight
  },
  //绘制圆角矩形
  roundRect(ctx, x, y, w, h, r) {
    // 开始绘制
    ctx.beginPath()
    // 左上角
    ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)

    // border-top
    ctx.moveTo(x + r, y)
    ctx.lineTo(x + w - r, y)
    ctx.lineTo(x + w, y + r)
    // 右上角
    ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)

    // border-right
    ctx.lineTo(x + w, y + h - r)
    ctx.lineTo(x + w - r, y + h)
    // 右下角
    ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)

    // border-bottom
    ctx.lineTo(x + r, y + h)
    ctx.lineTo(x, y + h - r)
    // 左下角
    ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)

    // border-left
    ctx.lineTo(x, y + r)
    ctx.lineTo(x + r, y)

    // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
    ctx.fill()
    // ctx.stroke()
    ctx.closePath()
    // 剪切
    ctx.clip()
  },

  // 获取echarts临时文件路径，需要修改源码ec-canvas.js
  getChartImage(id) {
    return new Promise((resolve, reject) => {
      //id示例，"#id"，ec-echarts的canvas-id
      const ec = this.selectComponent(id)
      ec.canvasToTempFilePath({
        success: res => {
          // console.log(res)
          resolve(res.tempFilePath)
        },
        fail: res => {
          console.log("fail:", res)
          reject()
        }
      })
    })
  },
  /**
   * 获取网络图片
   */
  getNetworkImage(url) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: url,
        success: res => {
          resolve(res)
        },
        fail: res => {
          console.log("fail:", res)
          reject()
        }
      })
    })
  },
  async saveResult() {
    await this.bindShare()
  },
  getList(string, arr) {
    let list = []
    string.replace(arr, (match, capture) => {
      list.push(capture);
    });
    return list;
  },
  checkAuthSetting(tempFilePath) {
    wx.getSetting({
      success: (res) => {
        //是否已授权
        if (res.authSetting['scope.writePhotosAlbum']) {
          //已授权直接保存
          this.saveImageToPhotosAlbum(tempFilePath)
        }
        //未授权请求授权
        else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => {
              //授权后保存
              this.saveImageToPhotosAlbum(tempFilePath)
            },
            fail: () => {
              wx.showToast({
                title: '您没有授权，无法保存到相册',
                icon: 'none'
              })
            }
          })
        }
        //用户拒绝授权后，无法再直接调起请求授权，需要用户自己去设置
        else {
          wx.openSetting({
            success: (res) => {
              if (res.authSetting['scope.writePhotosAlbum']) {
                //用户设置后保存
                this.saveImageToPhotosAlbum(tempFilePath)
              } else {
                wx.showToast({
                  title: '您没有授权，无法保存到相册',
                  icon: 'none'
                })
              }
            }
          })
        }
      }
    })
  },
  saveImageToPhotosAlbum(tempFilePath) {
    //保存
    wx.saveImageToPhotosAlbum({
      filePath: tempFilePath,
      success: (res) => {
        wx.hideLoading();
        wx.showToast({
          title: '保存成功',
          icon: 'none'
        })
      },
      fail: () => {}
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '德道升学',
      path: '/pages/test/index'
    }
  },
  goto(e) {
    wx.navigateTo({
      url: '/pages/test/question/index',
    })
  }
})